package com.seat.controller.User;
import com.seat.pojo.dto.*;
import com.seat.pojo.entrity.User;
import com.seat.service.UserService;
import com.seat.utils.EmailUtil;
import com.seat.utils.JwtUtil;
import com.seat.utils.Md5Util;
import jakarta.websocket.server.PathParam;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.seat.pojo.Result;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import static com.seat.constant.MessageConstant.*;


@RestController
@RequestMapping("/user")
@Validated
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JavaMailSender javaMailSender;// 邮件服务器

//     发送邮箱验证码，储存到redis里面
    @GetMapping("/email")
    public Result sendEmailVerCode(String email) {
        // 创建邮件消息
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("3504144526@qq.com");//必须写与配置相同的QQ邮箱
        message.setTo(email);//设置接收用户的邮箱
        message.setSubject("验证码");
        // 生成 6 位数字验证码
        Random random = new Random();
        int verificationCode = random.nextInt(899999) + 100000;
        message.setText("验证码: " + verificationCode);
//        将验证码储存到redis里面，设置有效时间60秒
    redisTemplate.opsForValue().set("code",verificationCode,1, TimeUnit.MINUTES);
        // 发送邮件
        javaMailSender.send(message);
        // 将验证码返回前端（通过前端直接验证即可）
        return Result.success(verificationCode);
    }


    @PostMapping("/register")
    public Result register( @RequestBody RegisterDTO register) {

        //查询用户
        User u = userService.findByUserName(register.getUsername());
        if (u == null) {
            //没有占用
            //注册
            userService.register(register);
            return Result.success();
        } else {
            //占用
            return Result.error(ACCOUNT_FOUND);
        }
    }



    @PostMapping("/login")
    public Result<String> login(@RequestBody  LoginDTO login) {
        log.info("用户登录{}",login);
        //根据用户名查询用户
        User loginUser = userService.findByUserName(login.getUsername());
        //判断该用户是否存在
        if (loginUser == null) {
            return Result.error(ACCOUNT_NOT_FOUND);
        }
        log.info("密码：{}",Md5Util.getMD5String(login.getPassword()));

        //判断密码是否正确  loginUser对象中的password是密文
        if (Md5Util.getMD5String(login.getPassword()).equals(loginUser.getPassword())) {
            //登录成功
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", loginUser.getId());
            claims.put("username", loginUser.getUsername());
            String token = JwtUtil.genToken(claims);
//            验证验证码是否正确
//            if(login.getCaptcha().equals(code))
//            {
//                //  TODO 增加redis
//
//                return Result.success(token);
//            }

            return Result.success(token);
        }
        return Result.error(PASSWORD_ERROR);
    }


    @PutMapping("/updatePwd")
    public Result updatePwd(@RequestBody UpdatePasswordDTO pwd, @RequestHeader("Authorization") String token) {

        log.info("修改密码{}",pwd.getUsername());
      User user=userService.findByUserName(pwd.getUsername());
      if(user.getPassword().equals(Md5Util.getMD5String(pwd.getOldPassword())))
      {
          userService.UpdatePassword(Md5Util.getMD5String(pwd.getNewPassword()));
          return Result.success();
      }
        return Result.success(PASSWORD_EDIT_FAILED);
    }


    //    TODO 更新头像，先获取头像地址
    @PatchMapping("/updatePic")
    public Result updatePic(@RequestParam @URL String PicUrl,@RequestParam String username)
    {
        log.info("更换头像{}",PicUrl);
        userService.UpdatePic(PicUrl,username);
        return Result.success();
    }


//     TODO 更新昵称
    @PutMapping("/updateNickname")
    public Result updateNickname(@RequestBody UpdateNicknameDTO updatePIc)
    {
        log.info("更换昵称{}",updatePIc.getUsername());
        userService.UpdateNickname(updatePIc);
        return Result.success();
    }


//     TODO 替换邮箱
    @PutMapping("/updateEmail")
    public Result updateEmail(@RequestBody UpdateEmailDTO updateEmail)
    {
        log.info("更新邮箱{}",updateEmail);
      String code=EmailUtil.SendEemail(updateEmail.getOldEmail());
        if(code.equals(updateEmail.getCaptcha()))
        {
            userService.updateEmail(updateEmail);
            return Result.success();
        }

        return Result.error(CAPTCHA_ERROR);
    }

//


}
